<template>
  <div>
    <el-form
      :model="postForm"
      ref="postForm"
      :rules="rules"
      label-width="120px"
      label-suffix=":"
      inline
    >
      <sticky :z-index="10" :class-name="'sub-navbar ' + postForm.status">
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">
          保存
        </el-button>
      </sticky>

      <div class="app-container" style="padding: 10px 20px">
        <h3 v-if="postForm.role">角色: <span style="color: red">{{postForm.role.name}}</span></h3>
        <el-divider></el-divider>
        <p>请勾选菜单:</p>
        <el-row>
          <el-col :span="24">
            <el-form-item v-for="(item, index) in list" :key="index" style="width: 200px">
              <el-checkbox v-model="item.selected" :label="`${item.name}(${item.url})`"></el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

    </el-form>
  </div>
</template>

<script>
import Sticky from '@/components/Sticky'
import api from '@/api'
export default {
  name: 'RoleMenu',
  components: {
    Sticky
  },
  data() {
    return {
      postForm: {
        status: 'draft'
      },
      list: [],
      selectedList: [],
      rules: {
      },
      loading: false,
      id: 0
    }
  },
  created() {
    this.id = this.$route.params.id
    this.fetchData()
  },
  methods: {
    async fetchData() {
      const { data } = await api.role.menuList({ id: this.id })
      this.postForm = Object.assign({}, data)
      // console.log(this.postForm)
      this.postForm.status = 'publisher'
      // all list
      this.list = this.postForm.list
      // selected list
      if (this.postForm.selected) {
        this.selectedList = this.postForm.selected
      }
      // console.log(this.selectedList)
      // select status
      this.list.forEach(x => {
        if (this.selectedList.includes(x.id)) {
          this.$set(x, 'selected', true)
        } else {
          this.$set(x, 'selected', false)
        }
      })
    },
    submitForm() {
      this.$refs.postForm.validate(validate => {
        if (validate) {
          this.loading = true
          const selected = this.list.filter(x => x.selected).map(x => x.id)
          api.role.saveMenu({
            selected,
            id: this.id
          }).then(response => {
            this.$notify({
              title: '成功',
              message: response.message || '保存成功',
              type: 'success',
              duration: 2000
            })
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        }
      })
    }
  }
}
</script>
